<?php
namespace api\modules\v1\models;

use api\common\models\User;
use yii\base\Model;
use Yii;
use common\records\UserInfo;
use common\records\Record;
use common\helpers\Aes;
use api\common\tools\WxBizDataCrypt;

class LoginForm extends Model
{
    public $code;
    public $encryptedData;
    public $iv;
    public $rememberMe = true;
    private $_user;

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            // openid is required
            [['code','encryptedData','iv'], 'required'],
            [['code','encryptedData','iv'], 'string'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
        ];
    }
    public function attributeLabels()
    {
        return [
            'rememberMe' => '记住我',
        ];
    }
    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array  $params    the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        return true;
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        $data = self::Wxlogin();
        $unionid = $data[0];
        $openid = $data[1];
        if($openid == "error" || count($data) != 8)
        {
            return false;
        }
        $gender = $data[2];
        $nick = $data[3];
        $photo = $data[4];
        $country = $data[5];
        $province = $data[6];
        $city = $data[7];
        $user = null;
        if($unionid != "error")
        {
            $user = UserInfo::find()->where(['unionid'=>$unionid])->one();
        }
        if($user == null)
        {
            $user = UserInfo::find()->where(['openid'=>$openid])->one();
        }
        if($user == null)
        {
            $user_info = new UserInfo();
            $user_info->openid = $openid;
            if($unionid != "error")
            {
                $user_info->unionid = $unionid;
                $user_info->uid = base64_encode($unionid);
            }else{
                $user_info->unionid = "";
                $user_info->uid = base64_encode($openid);

            }
            $user_info->photo = $photo;
            $user_info->nick = $nick;
            $user_info->country = $country;
            $user_info->province= $province;
            $user_info->city = $city;
            $user_info->gender= $gender;
            $time_now = date('Y-m-d H:i:s',time());
            
            $user_info->updated_at = $time_now;
            $user_info->created_at= $time_now;
            $user_info->coin = 0;
            //$user_info->generateAccessToken();
            $token = Yii::$app->security->generateRandomString();
            $user_info->access_token = $token;
            $user_info->expired_at = time() + 60 * 60;//60 * 60 * 24 * 30;
            //require_once 'phpqrcode/phpqrcode.php';
            $content = $user_info->uid.":".$token;
            $code_name = $user_info->uid.time().".png";
            $res = self::qrcode($content,$code_name);
            //QRcode::png($content, Yii::getAlias('@root/web/storage/upload/'.$code_name), QR_ECLEVEL_L, 3);
            $user_info->qrcode =Yii::$app->params['http']."://".$_SERVER['HTTP_HOST'].Yii::$app->params['projectName']."/web/storage/upload/".$code_name."?timestamp=".time();

            $user_info->save();
        }else{
            if($unionid != "error")
            {
                $user->unionid = $unionid;
                $user_old = UserInfo::find()->where(['openid'=>$openid])->one();
                if($user_old != null)
                {
                    if($user_old->unionid == "")
                    {
                        $user->coin = $user_old->coin+$user->coin;
                        $user_old->delete();
                    }
                }
            }
            $user->openid = $openid;
            $user->photo = $photo;
            $user->updated_at = date('Y-m-d H:i:s',time());
            $token = Yii::$app->security->generateRandomString();
            $user->access_token = $token;
            $user->expired_at = time() + 60 * 60;//60 * 60 * 24 * 30;
            //require_once 'phpqrcode/phpqrcode.php';
            $content = $user->uid.":".$token;
            $code_name = $user->uid.time().".png";
            $res = self::qrcode($content,$code_name);
            //QRcode::png($content, Yii::getAlias('@root/web/storage/upload/'.$code_name), QR_ECLEVEL_L, 3);
            $user->qrcode =Yii::$app->params['http']."://".$_SERVER['HTTP_HOST'].Yii::$app->params['projectName']."/web/storage/upload/".$code_name."?timestamp=".time();

            $user->save(false);
        }
        if ($this->validate()) {
            if($unionid != "error")
                return Yii::$app->user->login($this->getUser($unionid,1), $this->rememberMe ? 3600 * 24 * 30 : 0);
            else
                return Yii::$app->user->login($this->getUser($openid,2), $this->rememberMe ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }

    /**
     * Finds user by [[username]].
     *
     * @return User|null
     */
    protected function getUser($id, $type)
    {
        if ($this->_user === null) {
            if($type == 1)
                $this->_user = UserInfo::findByUnionid($id);
            else
                $this->_user = UserInfo::findByOpenid($id);
        }

        return $this->_user;
    }
    private function Wxlogin()
    {
        $user_info_url = Yii::$app->params['pay']['auth_url'];
        $appid = Yii::$app->params['pay']['APPID'];
        $secret = trim(Yii::$app->params['pay']['APPSECRET']);
        $grant_type = Yii::$app->params['pay']['grant_type'];
        $js_code = $this->code;
        $user_info_url = sprintf("%s?appid=%s&secret=%s&js_code=%s&grant_type=%s",$user_info_url,$appid,$secret,$js_code,$grant_type);
        
        $weixin_user_data = json_decode(self::curl_get_https($user_info_url),true);

        if(!array_key_exists("session_key", $weixin_user_data))
        {
            return ["error","error"];
        }
        $session_key = $weixin_user_data['session_key'];
        $openid = $weixin_user_data['openid'];
        $unionid = "error";
        if(array_key_exists("unionid", $weixin_user_data))
        {
            $unionid = $weixin_user_data['unionid'];
        }
        
        //return [$unionid,$openid];
        $data = null;
        $wxBizDataCrypt = new WxBizDataCrypt($appid, $session_key);
        $errCode=$wxBizDataCrypt->decryptData($this->encryptedData, $this->iv, $data );
//        var_dump($data);exit;
        if($data == null)
        {
            return ["error","error"];
        }else
        {
            $user_info = json_decode($data,true);
            //$unionid = $user_info['unionId'];
            $sex = $user_info['gender'];
            $nick= $user_info['nickName'];
            $photo = $user_info['avatarUrl'];
            $country = $user_info['country'];
            $province = $user_info['province'];
            $city = $user_info['city'];
            return [$unionid, $openid,$sex,$nick,$photo,$country,$province,$city];
        }
        return ["error",$openid];

    }

    function get_url ($url,$cookie=false)
    {
        $url = parse_url($url);
        $query = $url['path']."?".$url['query'];
        $result = null;
        $fp = fsockopen( $url['host'], 443 , $errno, $errstr, 30);
        if (!$fp) {
            return false;
        } else {
            $request = "GET $query HTTP/1.1 \r\n";
            $request .= "Host: ".$url['host']. " \r\n";
            $request .= "Connection: Close \r\n";
            if($cookie) $request.="Cookie:  ".$cookie."\n";
            $request.="\r\n";
            fwrite($fp,$request);
            while(!@feof($fp)) {
                $result .= @fgets($fp, 1024);
            }
            fclose($fp);
            return $result;
        }
    }
    function curl_get_https($url){
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, TRUE); // 跳过证书检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }
    function qrcode($content, $code_name)
    {
        $url = Yii::$app->params['url']['qrcode'];
        $post_data = array();
        $post_data["content"] = $content;
        $post_data["name"] = $code_name;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $output=curl_exec($ch);
        curl_close($ch);
        return print_r($output,true);
    }
}
